<template>
  <div class="main-box">
    <!-- 标题 -->
    <div class="title" style="background-color: white">
      <van-nav-bar
          title="商品详情"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
      />
    </div>
    <!-- 图片展示、名字、标题-->
    <div class="goods-img">
      <div class="item-img">
        <van-image
            width="100%"
            height="250"
            :src="goodsDetail.img === undefined ?'':imgsrc+goodsDetail.img"
        />
      </div>
      <div class="item-price" v-show="showPrice" style="margin-left: 10px;">
        <span style="color: #F2270C;">￥<span style="font-size: 30px;">{{goodsDetail.price}}</span></span>
      </div>

      <div class="item-price" v-show="showKillPrice" style="margin-left: 10px;">
        <span style="color: #F2270C;">￥<span style="font-size: 20px;text-decoration:line-through;">{{goodsDetail.price}}</span></span>
        <span style="color: #F2270C;">￥<span style="font-size: 30px;">{{goodsDetail.seckillPrice}}</span></span>
      </div>
      <!--优惠券模块-->
      <div style="margin-top:10px;margin-left: 10px" v-show="showCoup">
        <van-row type="flex" justify="space-between">
          <van-col span="4"><van-tag type="warning" size="large">大促券</van-tag></van-col>
          <van-col span="4"><div style="font-size:14px;color: red" @click="opendetail()">领券></div></van-col>
        </van-row>
        <van-action-sheet v-model="actionShow" title="优惠券">
          <div style="height:200px">
            <div class="grad1">
              <div v-for="(item,i) in bigSalecoup" :key="i">
                <div style="font-size:16px;width:40px;color: white;padding-top:40px;margin-left:10px">
                  {{item.usedAmount}}折
                </div>
                <div style="font-size:12px;width:185px;margin-top:-45px;margin-left:65px;">
                  <div>
                    满 ￥{{item.withAmount}} 可用
                  </div>
                  <div>
                    {{item.name}}
                  </div>
                  <div>
                    {{item.startTime}}
                  </div>
                  <div>
                    {{item.txt}}
                  </div>
                </div>
              </div>
            </div>
            <div style="margin-left:120px;">
              <van-button type="danger" @click="getCoup">立即领取</van-button>
            </div>
          </div>
        </van-action-sheet>

      </div>
      <div class="item-name" style="margin-top:10px;width:90%;margin-left: auto;margin-right: auto">
        <span style="font-size: 12px; background-color: #FF0000; color: white; padding: 2px 2px; border-radius: 2px;">{{goodsDetail.name}}</span>
        <span style="font-weight: 700; margin-left: 5px">{{goodsDetail.title}}</span>
      </div>
    </div>
    <!-- 规格参数-->
    <div class="goods-param" style="margin-top: 10px">
        <van-cell-group>
            <van-cell title="选择" value=">" @click="show = !show" />
        </van-cell-group>
    </div>
      <!-- 弹出sku-->
      <div class="goods">
        <!--        :goods-id="goodsId"
          :quota-used="quotaUsed"
                :initial-sku="initialSku"-->
        <van-sku
            v-model="show"
            stepper-title="我要买"
            :sku="sku"
            :goods="goods"
            :hide-stock="hideStock"
            show-add-cart-btn
            @stepper-change="buyNum"
            @buy-clicked="onBuyClicked"
            :show-add-cart-btn="showAddcart"
            @add-cart="onAddCartClicked"
        >
          <!-- 自定义 sku-header-price -->
          <template #sku-header-image-extra="props">
            <van-image
                :src="imgsrc+goodsDetail.img"
            />
          </template>
          <template #sku-header-price="props">
            <div class="van-sku__goods-price">
              <span class="van-sku__price-symbol">￥</span>
              <div v-show="killPrice">
                <span class="van-sku__price-num">{{goodsDetail.seckillPrice}}</span>
              </div>
              <div v-show="offenPrice">

                <span class="van-sku__price-num">{{goodsDetail.price}}</span>
              </div>
            </div>
          </template>
          <template #sku-group="props">
            <div style="margin-left: 20px" >颜色
              <div style="margin-top:10px">
                <van-radio-group v-model="colorRadio" direction="horizontal">
                  <template v-for="(item,i) in colorList">
                    <van-radio :name="item.id" @click="colorChoose" :key="i">{{item.colorName}}</van-radio>
                  </template>
                </van-radio-group>
              </div>
            </div>
            <div style="margin-left: 20px;margin-top:10px" >尺寸
              <div style="margin-top:10px">
                <van-radio-group v-model="sizeRadio" direction="horizontal">
                  <template v-for="(item,i) in sizeList">
                    <van-radio :name="item.id"  @click="sizeChoose" :key="i">{{item.sizeName}}</van-radio>
                  </template>
                </van-radio-group>
              </div>
            </div>
          </template>
        </van-sku>
      </div>
      <!-- 商品评价 -->
      <div class="title">
          <!--          <label>宝贝评价</label>-->
          <van-cell-group>
              <van-cell title="评价" value="查看全部评价>" @click="showAllEva" />
          </van-cell-group>
      </div>
      <div class="evaluate" style="width:90%; margin-left: auto;margin-right: auto">
        <div style="margin-top:10px;margin-bottom:100px">
          <template v-for="(item,i) in eva.slice(0,3)">
            <van-row gutter="20" :key="i">
              <van-col span="4"> <van-image
                  round
                  width="50px"
                  height="50px"
                  src="https://img01.yzcdn.cn/vant/cat.jpeg"
              /></van-col>
              <van-col span="20"><label style="font-size: 14px">{{item.userName}}</label><br>
                <label  style="font-size:12px">{{item.message}}</label></van-col>
            </van-row>
          </template>

        </div>
      </div>
      <!-- 商品导航 -->
      <div class="navigate">
        <van-goods-action>
          <!--        <van-goods-action-icon icon="chat-o" text="客服" dot />-->
          <van-goods-action-icon icon="cart-o"  @click="gocart()" text="购物车" :badge="cartNum"/>
          <van-goods-action-button v-show="showAddCart" type="warning"   @click="addcart();show = !show" text="加入购物车" />
          <van-goods-action-button  type="warning" v-show="showTime">
            <!--                        <van-count-down  millisecond :time="killTime" :auto-start="autoStart" @finish="shop" format="HH:mm:ss:SS" />-->
            <van-count-down  millisecond :time="killTime-sendTime>0?killTime-sendTime:0" :auto-start="autoStart"   @finish="shop" format="HH:mm:ss:SS" />
          </van-goods-action-button>
          <van-goods-action-button  type="warning"  v-show="showNoBegin" text="活动未开始">
          </van-goods-action-button>
          <van-goods-action-button  type="warning"  v-show="showOver" text="活动已结束">
          </van-goods-action-button>
          <van-goods-action-button type="danger" v-show="showBuy" :disabled="dis"   @click="nowbuy();show = !show;"  text="立即购买" />
          <van-goods-action-button type="danger" v-show="showBuyOver" text="已抢完" />
        </van-goods-action>
      </div>
    </div>
</template>

<script >
import {
  getGoodsDetail,
  putCart,
  getInventory,
  getBigSalecoup,
  getIsHavecoup,
  putCoup,
  buyNow,
  getInventoryAvail, getKill, cartGoodsList, killBuyNow,
} from "@/api/api"
import img from "@/api/api"
import {Toast} from "vant";
import {mapMutations} from "vuex";



export default {
  name:"goodDetail",
  gid:0,
  cid:0,


  created() {
    this.aid=this.$route.query.aid;
    if(this.$route.query.aid==2) {
      this.showAddcart=false;
      //获取商品goodsId
      this.goodsId= this.$route.query.goodId;

      let data1=JSON.parse(localStorage.getItem(this.goodsId));

     if(data1===null){

       getGoodsDetail(this.$route.query.goodId).then((response) => {
         if (response.data.code === 2000) {

           //获取数据后存入localStorage中
           localStorage.setItem(this.goodsId, JSON.stringify({

             goodstxtInfo:response.data.data.goodsVo,
             inventoryInfo:response.data.data.inventoryList,
             evaInfo:""
           }));

           let num = response.data.data.goodsVo.seckillNum
           if (num <= 0) {
             this.showBuy = false
             this.showBuyOver = true
           } else {
             this.showBuy = true
             this.showBuyOver = false
           }
         } else {
           Toast(response.data.message);
         }
       });
     }else{
       let num =data1.goodstxtInfo.seckillNum
       if (num <= 0) {
         this.showBuy = false
         this.showBuyOver = true
       } else {
         this.showBuy = true
         this.showBuyOver = false
       }
     }
      var time = new Date(new Date().getTime());
      var year = time.getFullYear();
      var month = time.getMonth()+1;
      var day = time.getDate();
      var hour = time.getHours();
      var minute = time.getMinutes();
      var second = time.getSeconds();
      this.nowTime=year+'-'+(month<10?'0'+month:month)+'-'+(day<10?'0'+day:day)+' '+(hour<10?'0'+hour:hour)+':'+(minute<10?'0'+minute:minute)+':'+(second<10?'0'+second:second)

      // this.nowTime=new Date(Date.parse(this.nowTime));
      getKill().then((response) => {
        if(response.data.code===2000){
          this.active=response.data.data.activityList
          for (let i = 0; i <this.active.length ; i++) {
            if(this.active[i].id==2)
            {
              this.nowTime=new Date(Date.parse(this.nowTime));
              this.killStartTime=new Date(Date.parse(this.active[i].startTime));
              this.killEndTime=new Date(Date.parse(this.active[i].endTime));
              this.showAddCart = false;
              this.showPrice = false;
              this.showKillPrice = true;
              this.showCoup = false;
              if(this.nowTime<this.killStartTime){
                this.showNoBegin=true;
                this.dis=true;
              }
              else if(this.nowTime>=this.killStartTime&&this.nowTime<=this.killEndTime){
                this.killPrice=true;
                this.offenPrice=false;
                this.autoStart=true;
                this.showNoBegin=false;
                this.showTime=true;
                this.showOver=false;
                this.dis=false;

              }
              else if(this.nowTime>this.killEndTime){
                console.log("zouzheli")
                this.dis=false;
                this.showNoBegin=false;
                this.showOver=true;
                this.dis=true;
                this.showTime=false;
                // this.showKillPrice=false;
                // this.showPrice=false;
                this.killPrice=true;
                this.offenPrice=true;
                this.showAddcart=true;
                this.shop();
              }
            }
          }
        }else{

          Toast(response.data.message);
        }
      });
    }else if(this.$route.query.aid==1) {
      this.showAddCart = true;
      this.showPrice = true;
      this.showKillPrice = false;
      this.showCoup = true;
    }else if(this.$route.query.aid==0){
      this.showAddCart = true;
      this.showPrice = true;
      this.showKillPrice = false;
      this.showCoup = false;
    }
    this.gid=this.$route.query.goodId
    //获取商品goodsId，，，，获取商品信息
    this.goodsId= this.$route.query.goodId;

    let data1=JSON.parse(localStorage.getItem(this.goodsId));
    console.log("缓存中的data1---"+data1);
    if (data1===null){
      console.log("缓存中无有数据走到了这里")
      getGoodsDetail(this.gid).then((response) => {
        if(response.data.code===2000){

          //获取数据后存入localStorage中
          localStorage.setItem(this.goodsId, JSON.stringify({

            goodstxtInfo:response.data.data.goodsVo,

            inventoryInfo:response.data.data.inventoryList,
            evaInfo:response.data.data.evaList
          }));
          this.shopCart.push(response.data.data.goodsVo)
          this.goodsDetail=response.data.data.goodsVo
          this.colorList=response.data.data.inventoryList.colorList
          this.sizeList=response.data.data.inventoryList.sizeList
          this.eva=response.data.data.evaList
        }else{
          Toast(response.data.message);
        }
      });

    }else{
      console.log("缓存中有数据走到了这里")
      this.shopCart.push(data1.goodstxtInfo)
      this.goodsDetail=data1.goodstxtInfo
      this.colorList=data1.inventoryInfo.colorList
      this.sizeList=data1.inventoryInfo.sizeList
      this.eva=data1.evaInfo
    }
    this.token= localStorage.getItem("token");
    if (this.token==="null" || this.token=== '' || this.token===undefined||this.token===null){
      Toast("未登录")
    }else{
      cartGoodsList().then((response) => {
        if(response.data.data.cartInfo!==undefined)
          this.cartNum = response.data.data.cartInfo.length;
      });
    }
    getInventoryAvail().then((response) => {
      if(response.data.code===2000){
        this.sku.stock_num=response.data.data.availSum;
      }else{
        Toast(response.data.message);
      }

    });
    getBigSalecoup(2).then((response) => {
      if(response.data.code===2000){
        this.bigSalecoup=response.data.data.coupons
        this.cid=response.data.data.coupons.id
      }else{
        Toast(response.data.message);
      }
    });

  },
  computed:{
    sendTime(){
      let dateStr = this.killStartTime;
      let before = new Date(dateStr);
      let now = new Date();
      let result = now.getTime()-before.getTime();
      return result;
    },
  },
  data() {

    return {
      goodsId:"",
      dis:false,
      showAddcart:true,
      killPrice:false,
      offenPrice:true,
      aid:0,
      showBuy:true,
      showBuyOver:false,
      autoStart:false,
      killStartTime:"",
      killEndTime:"",
      num: 0,
      timer: null,
      showOver:false,
      showBegin:false,
      showNoBegin:false,
      nowTime:"",
      cartNum:0,
      showKillPrice:false,
      showPrice:true,
      killTime:1*60*60*1000,
      // killTime:1*60,
      showTime:false,
      showAddCart:false,
      showCoup:false,
      hideStock:false,
      inventorynum:0,
      shopCart: [],
      goodsTwoId:0,
      bigSalecoup:[],
      actionShow:false,
      showPopover: false,
      goodsDetail:[],
      colorRadio: '0',
      sizeRadio:'0',
      inventory:[],
      product_number:1, //  选中的产品数量
      imgsrc:img.src,
      eva:[],
      sizeRadioChoose:0,
      colorRadioChoose:0,
      colorList:[],
      sizeList:[],
      goodsInfo:[],
      show: false,
      sku: {
        tree: [
          {
            k: '颜色', // skuKeyName：规格类目名称
            k_s: 's1', // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: [
              {
                id: '1', // skuValueId：规格值 id
                name: '红色',},// skuValueName：规格值名称
              {
                id: '1',
                name: '蓝色',
              }
            ],
            largeImageMode: true, //  是否展示大图模式
          }
        ],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [
          {
            id: 2259, // skuId
            s1: '1', // 规格类目 k_s 为 s1 的对应规格值 id
            s2: '1', // 规格类目 k_s 为 s2 的对应规格值 id
            price: 100, // 价格（单位分）
            // stock_num: 110 // 当前 sku 组合对应的库存
          }
        ],
        price: '1.00', // 默认价格（单位元）
        collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: true, // 是否无规格商品
        hide_stock: false,
        stock_num:0,
      },
      goods: {
        picture: 'imgsrc+goodsDetail.img'
      },
      // messageConfig: {
      //     // 数据结构见下方文档
      // },
    };
  }
  ,
  methods: {
    ...mapMutations(["saveShopCart"]),
    buyNum(data) {
      this.product_number = data;
      console.log("shuliang"+data);
    },
      showAllEva(){
          this.$router.push({
              path: '/evaluate',
              query: {
                  gid: this.gid
              }
          })
      },
    getCoup() {
      getIsHavecoup(1, 1).then((response) => {
        if (response.data.data.results === 0) {
          putCoup(2).then((response) => {
            Toast('领取成功');
          })
        } else {
          Toast('账户里已经有该优惠券了');
        }
      })
    },
    opendetail() {
      this.actionShow = true
    },
    shop() {
      this.showTime=false;
      this.showOver=true;
      // this.showKillPrice=false;
      // this.showPrice=true;
    },
    onBuyClicked() {
      if (this.colorRadioChoose == 0||this.sizeRadioChoose == 0) {
        Toast("请选择颜色或尺寸")
      }else {
        getGoodsDetail(this.$route.query.goodId).then((response) => {
          if (response.data.code === 2000) {
            let num = response.data.data.goodsVo.seckillNum
            if (num <= 0) {
              this.showBuy = false
              this.showBuyOver = true
            } else {
              this.showBuy = true
              this.showBuyOver = false
            }
          } else {
            Toast(response.data.message);
          }
        });

        var dateTime=new Date();
        dateTime=new Date(dateTime);
        dateTime=new Date(Date.parse(dateTime));
        if(dateTime==this.killEndTime){
          Toast("活动已结束");
          this.shop();
        }
        this.shopCart[0].count = this.product_number;
        this.saveShopCart(this.shopCart);
        if (this.sku.stock_num != 0) {
          if (this.aid == 0||this.aid==1) {
            buyNow(this.gid, this.colorRadio, this.sizeRadio, this.product_number).then((response) => {
              if(response.data.code===2000){
                this.goodsTwoId = response.data.data.goodsTwoId
                this.$router.push({
                  path: '/confirmOrder',
                  query: {
                    // userId: 1,
                    goodsTwoId: this.goodsTwoId,
                    state: 2,
                    aid: this.aid,
                    killEndTime: this.killEndTime
                  }
                })
              }else if(response.data.code===2001){
                Toast(response.data.message)
              }
            })
          }
          else if(this.aid == 2){
            killBuyNow(this.gid, this.colorRadio, this.sizeRadio, this.product_number).then((response) => {
              if(response.data.code===2000) {
                this.goodsTwoId = response.data.data.goodsTwoId
                this.$router.push({
                  path: '/confirmOrder',
                  query: {
                    // userId: 1,
                      goodid:this.gid,
                    goodsTwoId: this.goodsTwoId,
                    state: 2,
                    aid: this.aid,
                    killEndTime: this.killEndTime
                  }
                })
              }else if(response.data.code===2001){
                Toast("服务器内部错误")
              }else if(response.data.code===2003){
                Toast("手慢了，已抢光")
              }
            })

          }
          // let result = [];
          // Object.values(this.shopCart).forEach((goods, index) => {
          //         result.push(goods);
          // })
          // this.saveShopCart(this.shopCart);
        }
      }
    },
    addcart(){
      this.token= localStorage.getItem("token");
      if (this.token==="null" || this.token=== '' || this.token===undefined||this.token===null){
        this.$router.push("/login")
      }
    },
    nowbuy(){
      this.token= localStorage.getItem("token");
      if (this.token==="null" || this.token=== '' || this.token===undefined||this.token===null){
        this.$router.push("/login")
      }
    },
    onAddCartClicked() {

      if (this.colorRadioChoose == 0||this.sizeRadioChoose == 0) {
        Toast("请选择颜色或尺寸")
      }else {
        if (this.sku.stock_num != 0) {
          console.log("到底试多少"+this.product_number)
          putCart(this.gid,this.colorRadio, this.sizeRadio,this.product_number).then((response) => {
            if (response.data.code == 2000) {
              Toast(response.data.message);
              this.product_number=1;
              this.show=false;


            } else {
              Toast(response.data.message)
            }
          });
        }
      }

    },
    onClickLeft() {
      // this.$router.push({path: '/dashBoard/Home'})
      this.$router.go(-1)
    }
    ,

    gocart() {
      this.$router.push({path: 'dashboard/cart'})
    },

    colorChoose() {
      if (this.colorRadioChoose == 0) {
        this.colorRadioChoose = 1
      } else {
        this.colorRadioChoose = 1
      }
      if (this.colorRadioChoose == 1 && this.sizeRadioChoose == 1) {
        getInventory(this.goodsDetail.id, this.colorRadio, this.sizeRadio).then((response) => {
          // if(Object.getOwnPropertyNames(response.data.data).length === 0){
          if (response.data.code === 2000) {
            // if(response.data.data.inventory==undefined){
            // this.sku.stock_num=0
            // }else{
            this.inventorynum = response.data.data.inventory.availNum
            this.sku.stock_num = this.inventorynum
            // }
          } else {
            this.sku.stock_num = 0
            // Toast(response.data.message);
          }
        })
      }

    },
    sizeChoose() {
      if (this.sizeRadioChoose == 0) {
        this.sizeRadioChoose = 1
      } else {
        this.sizeRadioChoose = 1
      }
      if (this.colorRadioChoose == 1 && this.sizeRadioChoose == 1) {
        getInventory(this.goodsDetail.id, this.colorRadio, this.sizeRadio).then((response) => {
          if (response.data.code === 2000) {
            // if(response.data.data.inventory==undefined){
            // this.sku.stock_num=0
            // }
            // else{
            this.inventorynum = response.data.data.inventory.availNum
            this.sku.stock_num = this.inventorynum
            // }
          } else {
            this.sku.stock_num = 0
            // Toast(response.data.message);
          }
        })
      }
    },
  }
};

</script>

<style>
.main-box{
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;

}
.content {
  padding: 16px 16px 160px;
}
.grad1 {
  margin-top:20px;
  margin-bottom:20px;
  width: 250px;
  height:100px;
  margin-left:60px;
  background: radial-gradient(circle at right top, transparent 10px,  #FF0000 0) top left / 60px 51% no-repeat,
  radial-gradient(circle at right bottom, transparent 10px, #FF0000 0) bottom left /60px 51% no-repeat,
  radial-gradient(circle at left top, transparent 10px, #FFFFFF 0) top right /190px 51% no-repeat,
  radial-gradient(circle at left bottom, transparent 10px,#FFFFFF 0) bottom right /190px 51% no-repeat;
  filter: drop-shadow(3px 3px 3px rgba(0,0,0,.3));
}
</style>